<!-- 商圈管理 -->
<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <GzSearchForm v-if="!props.sqlxNo" :searchFunc="searchFunc" :resetFunc="onReset" searchConditionNum="6">
        <a-form-item class="table-search-item">
          <GzTreeSelect ref="gzThreeRef" :isNeedDefault="false" v-model:value="searchData['agentNo']" />
        </a-form-item>
        <gz-text-up v-model:value="searchData['groupNo']" :placeholder="'商圈编号'" />
        <gz-text-up v-model:value="searchData['groupName']" :placeholder="'商圈名称'" />
        <!-- <gz-text-up
          v-model:value="searchData['sqlxText']"
          :placeholder="'商圈类型编号/类型名称'"
        /> -->
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="searchData['groupType']" placeholder="商圈类型">
            <!-- 商圈类型： 0商业综合体  1商务综合体  2生活综合体 3菜市场  4批发市场 -->
            <a-select-option value="0"> 商业综合体 </a-select-option>
            <a-select-option value="1"> 商务综合体 </a-select-option>
            <a-select-option value="2"> 生活综合体 </a-select-option>
            <a-select-option value="3"> 菜市场 </a-select-option>
            <a-select-option value="4"> 批发市场 </a-select-option>
          </a-select>
        </a-form-item>



        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="searchData['state']" placeholder="是否启用">
            <a-select-option value=""> 全部 </a-select-option>
            <a-select-option value="1"> 是 </a-select-option>
            <a-select-option value="0"> 否 </a-select-option>
          </a-select>
        </a-form-item>
      </GzSearchForm>
      <!-- 列表渲染 -->
      <GzTable ref="infoTableRef" :init-data="true" :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns" :search-data="searchData" row-key="groupId">
        <template #topBtnSlot>
          <a-button v-if="$access('ENT_GROUP_INFO_ADD') && !props.sqlxNo" type="primary" @click="addFunc">
            <plus-outlined />新建
          </a-button>
          <a-button v-if="$access('ENT_GROUP_INFO_EXPT')" type="primary" @click="exportFunc" :disabled="total == 0">
            <export-outlined />导出
          </a-button>
        </template>

        <template #headerCell="{ column }">
          <template v-if="column.key === 'mchYxNum'">
            <a-tooltip>
              <template #title>符合商圈位置判断、商户状态为开启的商户</template>
              <span> 商圈有效商户数<info-circle-outlined /> </span>
            </a-tooltip>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key.split('.')[0] === 'num'">
            <a>{{ record[column.key.split(".")[1]] || "" }}</a>
          </template>
          <template v-if="column.key === 'cityName'">
            {{ JSON.parse(record.areaName)[1] }}
          </template>
          <template v-if="column.key === 'areaName'">
            {{ JSON.parse(record.areaName)[2] }}
          </template>
          <template v-if="column.key === 'groupType'">
            <template v-if="record.groupType === 0">商业综合体</template>
            <template v-if="record.groupType === 1">商务综合体</template>
            <template v-if="record.groupType === 2">生活综合体</template>
            <template v-if="record.groupType === 3">菜市场</template>
            <template v-if="record.groupType === 4">批发市场</template>
          </template>
          <template v-if="column.key === 'state'">
            <template v-if="record.state === 0">未启用</template>
            <template v-if="record.state === 1">启用</template>
          </template>
          <template v-if="column.key === 'operation'">
            <!-- 操作列插槽 -->
            <GzTableColumns>
              <a-button v-if="$access('ENT_GROUP_INFO_EDIT')" type="link" @click="editFunc(record.groupId)">编辑</a-button>
              <a-button v-if="$access('ENT_GROUP_INFO_IMPT_MCH')" type="link" @click="importFun(record.groupId, '1')">商户导入</a-button>
              <a-button v-if="$access('ENT_GROUP_INFO_IMPT_MCH_RECORDS')" type="link" @click="importRecordFun(record.groupId)">商户导入记录</a-button>
              <a-button v-if="$access('ENT_GROUP_INFO_DELMCH')" type="link" @click="importFun(record.groupId, '2')">商户解绑</a-button>
              <a-button v-if="$access('ENT_GROUP_INFO_DEL_MCH_RECORDS')" type="link" @click="unBindRecordFun(record.groupId)">商户解绑记录</a-button>
              <a-button v-if="$access('ENT_GROUP_INFO_MCH')" type="link" @click="mchListFun(record.groupId)">商户明细</a-button>
              <a-button v-if="$access('ENT_GROUP_INFO_ACTE')" type="link" @click="activityListFun(record.groupId)">活动明细</a-button>
              <a-button v-if="$access('ENT_GROUP_INFO_DEL')" type="link" danger @click="deleteFunc(record.groupId)">删除</a-button>
            </GzTableColumns>
          </template>
        </template>
      </GzTable>
    </a-card>
  </page-header-wrapper>
  <!-- 选择活动平台以及类型 -->

  <!-- 新增页面组件  -->
  <InfoAddOrEdit ref="infoAddOrEdit" :callback-func="searchFunc" />

  <!-- 商户导入、商户解绑导入 -->
  <ImportMch ref="importMchRef" :callback-func="searchFunc" />

  <!-- 商户导入记录 -->
  <a-modal v-model:visible="vdata.importRecordVisible" width="1000px" title="商圈商户导入记录">
    <ImportRecord v-if="vdata.importRecordVisible" :sqNo="vdata.propSqNo" ref="importRecord" />
    <template #footer></template>
  </a-modal>

  <!-- 商户解绑记录 -->
  <a-modal v-model:visible="vdata.unBindRecordVisible" width="1000px" title="商圈商户解绑记录">
    <UnBindRecord v-if="vdata.unBindRecordVisible" :sqNo="vdata.propSqNo" ref="unBindRecord" />
    <template #footer></template>
  </a-modal>

  <!-- 商户明细 -->
  <a-modal v-model:visible="vdata.mchListVisible" width="1000px" title="商户明细">
    <MchList v-if="vdata.mchListVisible" :sqNo="vdata.propSqNo" ref="mchList" />
    <template #footer></template>
  </a-modal>

  <!-- 活动明细 -->
  <a-modal v-model:visible="vdata.activityVisible" width="1000px" title="活动明细">
    <ActivityList v-if="vdata.activityVisible" :sqNo="vdata.propSqNo" ref="activityList" />
    <template #footer></template>
  </a-modal>
</template>

<script lang="ts" setup>
import {
  req,
  API_URL_MARKETINGGROUP,
  API_URL_MARKETINGGROUP_REMOVE,
} from "@/api/manage";
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import InfoAddOrEdit from "./AddOrEdit.vue";
import ImportMch from "./ImportMch.vue";
import ImportRecord from "./ImportRecord.vue";
import UnBindRecord from "./UnBindRecord.vue";
import MchList from "./MchList.vue";
import ActivityList from "./ActivityList.vue";
const { $infoBox, $access } =
  getCurrentInstance()!.appContext.config.globalProperties;

import * as XLSX from "xlsx";
import { resolve } from "path";

// 商圈类型--查看下属商圈
const props = defineProps({
  sqlxNo: { type: String, default: "" },
});
// const AddOrEditRef = ref()
const vdata: any = reactive({
  importRecordVisible: false,
  unBindRecordVisible: false,
  mchListVisible: false,
  activityVisible: false,
  propSqNo: "",
});

const infoTableRef = ref();

console.log('infoTableRef', infoTableRef)
let tableColumns = reactive([
  {
    key: "cityName",
    title: "商圈所属地市",
    dataIndex: "cityName",
    fixed: "left",
    width: 140,
  },
  {
    key: "areaName",
    title: "商圈所属区县",
    dataIndex: "areaName",
    width: 140,
    minWidth: 140,
    maxWidth: 170,
  },
  {
    key: "agentNo",
    title: "商圈所属网点",
    dataIndex: "agentNo",
    width: 140,
    minWidth: 140,
    maxWidth: 170,
  },
  {
    key: "groupNo",
    title: "商圈编号",
    dataIndex: "groupNo",
    width: 140,
    minWidth: 140,
    maxWidth: 170,
  },
  {
    key: "groupName",
    title: "商圈名称",
    dataIndex: "groupName",
    width: 140,
    minWidth: 140,
    maxWidth: 170,
  },
  {
    key: "groupType",
    title: "类型名称",
    dataIndex: "groupType",
    width: 140,
    minWidth: 140,
    maxWidth: 170,
  },
  // { key: 'create', title: '创建人', dataIndex: 'create', width: 140, minWidth: 140, maxWidth: 170 },
  // { key: 'update', title: '最后修改人', dataIndex: 'update', width: 140, minWidth: 140, maxWidth: 170 },
  // { key: 'updateAt', title: '最后修改时间', dataIndex: 'updateAt',  width: 200, minWidth: 200, maxWidth: 230 },
  {
    key: "state",
    title: "是否启用",
    dataIndex: "state",
    width: 140,
    minWidth: 140,
    maxWidth: 170,
  },
  // { key: 'num.mchNum', title: '商圈商户数', dataIndex: 'mchNum',align: "center", width: 140, minWidth: 140, maxWidth: 170 },
  // { key: 'num.mchYxNum', title: '商圈有效商户数', dataIndex: 'mchYxNum',align: "center", width: 150, minWidth: 150, maxWidth: 170  },
  // { key: 'num.radius', title: '商圈辐射范围', dataIndex: 'radius',align: "center", width: 140, minWidth: 140, maxWidth: 170 },
  // { key: 'num.acticityNum', title: '累计活动数', dataIndex: 'acticityNum',align: "center", width: 140, minWidth: 140, maxWidth: 170 },
  // { key: 'num.acticityIngNum', title: '进行中活动', dataIndex: 'acticityIngNum',align: "center", width: 140, minWidth: 140, maxWidth: 170 },
  // { key: 'operation', title: '操作', dataIndex: 'operation',width:260, fixed: 'right', align: 'center' }
]);
if (!props.sqlxNo) {
  tableColumns.push({
    key: "operation",
    title: "操作",
    dataIndex: "operation",
    width: 260,
    fixed: "right",
    align: "center",
  });
}

const gzThreeRef = ref()
const searchData = ref({})
const infoAddOrEdit = ref()
const importMchRef = ref()
const total = ref(1)

// 请求table接口数据
function reqTableDataFunc(params: any) {
  console.log(6666, params);
  // var obj=Object.assign(params,{proxyNo:useUserStore().userInfo.belongInfoId})// 机构号
  // return req.list(API_URL_MARKETING_LIST, obj)
  return new Promise((resolve, reject) => {
    req.list(API_URL_MARKETINGGROUP, params).then(res => {
      total.value = res.total
      resolve(res)
    })

  })

}

function searchFunc() {
  infoTableRef.value.refTable(true);
}

function onReset() {
  searchData.value = {}
  gzThreeRef.value.clear()
}

// 导出商圈数据
const exportCodeData = ref([
  [
    "序号",
    "商圈所属地市",
    "商圈所属区县",
    "商圈所属网点",
    "商圈编号",
    "商圈名称",
    "类型名称",
    "是否启用",
  ],
]) as any

// excel表格导出函数数据
const exportToExcel = (item) => {
  // 创建一个工作簿
  const workbook = XLSX.utils.book_new();

  // 创建一个工作表
  const worksheet = XLSX.utils.aoa_to_sheet([...item]);

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

  // 生成Excel文件
  XLSX.writeFile(workbook, "data.xlsx");
};
const exportList = ref([])
function exportFunc() {
  req.list(API_URL_MARKETINGGROUP).then((res) => {
    res.records.forEach((item, index) => {
      exportCodeData.value.push([
        index + 1,
        JSON.parse(item.areaName)[1],
        JSON.parse(item.areaName)[2],
        item.agentNo,
        item.groupNo,
        item.groupDes,
        item.groupType == 0
          ? "商业综合体"
          : item.groupType == 1
            ? "商务综合体"
            : item.groupType == 2
              ? "生活综合体"
              : item.groupType == 3
                ? "菜市场"
                : item.groupType == 4
                  ? "批发市场"
                  : "",
        item.state == 0 ? '未启用' : '启用'
      ]);
    });
    exportToExcel(exportCodeData.value)
  });
}

function addFunc() {
  // 业务通用【新增】 函数
  infoAddOrEdit.value.show();
}
function editFunc(recordId: any) {
  // 业务通用【修改】 函数
  infoAddOrEdit.value.show(recordId);
}

// 导入商户
function importFun(recordId: any, type) {
  importMchRef.value.show(recordId, type);
}

// 导入商户记录
function importRecordFun(recordId: any) {
  vdata.propSqNo = recordId;
  vdata.importRecordVisible = true;
}
// 解绑商户记录
function unBindRecordFun(recordId: any) {
  vdata.propSqNo = recordId;
  vdata.unBindRecordVisible = true;
}

// 商户明细
function mchListFun(recordId: any) {
  vdata.propSqNo = recordId;
  vdata.mchListVisible = true;
}

// 商户明细
function activityListFun(recordId: any) {
  vdata.propSqNo = recordId;
  vdata.activityVisible = true;
}

// 删除商圈
function deleteFunc(groupId) {
  $infoBox.confirmDanger("确认删除？", "请确认是否删除当前商圈？", () => {
    req.add(API_URL_MARKETINGGROUP_REMOVE, { groupId }).then((res) => {
      $infoBox.message.success("删除成功！");
      infoTableRef.value.refTable(true);
    });
  });
}

onMounted(() => {
  if (props.sqlxNo) searchData["sqlxText"] = props.sqlxNo;
});
</script>
